<?php

/**
 * 验证生成类
 */
class Code
{
	protected $config =[
		'width'=>200,
		'height'=>100,
		'length'=>4,
		'bg'=>[255,255,255],
		'line'=>10,
		'font'=>50,
		'str'=>'qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM'
	];

	protected $src; //画布

	public function __construct($config=[])
	{
		$this->config = array_merge($this->config ,$config);
	}

	public function __get($name)
	{
		return $this->config[$name];
	}

	public function entry()
	{
		$this->create();
		$this->fill();
		$this->line();
		$this->font();
		$this->out();
	}

	protected function create()
	{
		$this->src = imageCreateTrueColor($this->width,$this->height);
	}

	protected function fill()
	{
		$color = imageColorAllocate($this->src,$this->bg[0],$this->bg[1],$this->bg[2]); 

		imageFill($this->src,0,0,$color);
	}
	protected function line()
	{
		for ($i=0; $i <$this->line ; $i++) { 
			$color = imageColorAllocate($this->src,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); 
			imageline ($this->src,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height) ,$color);
		}
	}
	protected function font()
	{
		for ($i=0; $i <$this->length ; $i++) { 

			$color = imageColorAllocate($this->src,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100)); 

			$str = $this->str[mt_rand(0,strlen($this->str)-1)];

			$y  = ($this->height+$this->font)/2;

			$x  = (($this->width/$this->length)-($this->font*0.35))/2+$i*($this->width/$this->length);

			imagettftext ($this->src,$this->font,mt_rand(-15,15), $x , $y ,$color , "./mplus-1m-regular.woff2.ttf" , $str);
		}
		
	}

	protected function out()
	{
		header("Content-type: image/png");

		imagepng($this->src);
	}

}